package com.lwbpro.system.domain.vo;

import cn.hutool.json.JSONUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.lwbpro.common.exception.ServiceException;

public class ExcelImportListener extends AnalysisEventListener {

    @Override
    public void invoke(Object data, AnalysisContext context) {
        int rowIndex = context.readRowHolder().getRowIndex() + 1;
        System.out.println("第" + rowIndex + "行, 解析到一条数据: " + JSONUtil.toJsonStr(data));
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {

    }

    // 重写此方法以便于收集错误数据
    @Override
    public void onException(Exception exception, AnalysisContext context) {
        // 调用以下封装的错误数据收集工具
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException convertException = (ExcelDataConvertException) exception;
            int row = convertException.getRowIndex();
            int column = convertException.getColumnIndex();
            throw new ServiceException("第" + row+ "行" + "数据格式有误！");
        }
    }
}
